package com.zlkj.pro.core.util;

import cn.hutool.http.HttpUtil;
import cn.stylefeng.roses.kernel.config.api.context.ConfigContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zlkj.pro.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

import static com.zlkj.pro.core.exception.enums.BusinessExceptionEnum.THE_EXPRESS_DELIVERY_SYSTEM_IS_BUSY;

/**
 * @author 孙铭泽
 * @date 2022/9/21
 * @time 15:27
 */
@Slf4j
public class ExpressBirdUtil {

    /**
     * Json方式 查询订单物流轨迹
     */
    public static JSONArray getOrderTracesByJson(String orderCode, String shipperCode, String logisticCode, String lastFourNumber) {
        try {
            //处理顺丰查询轨迹需手机号码后4位
            String requestData;
            if ("SF".equals(shipperCode)) {
                requestData = "{'OrderCode':'" + orderCode + "','shippercode':'" + shipperCode + "','LogisticCode':'" + logisticCode + "','CustomerName':'" + lastFourNumber + "'}";
            } else {
                requestData = "{'OrderCode':'" + orderCode + "','shippercode':'" + shipperCode + "','LogisticCode':'" + logisticCode + "'}";
            }
            Map<String, Object> params = new HashMap<>();
            params.put("RequestData", URLEncoder.encode(requestData, "UTF-8"));
            String businessId = ConfigContext.me().getConfigValueNullable("EXPRESS_BIRD_BUSINESS_ID", String.class);
            params.put("EBusinessID", businessId);
            params.put("RequestType", "8001");
            String dataSign = encrypt(requestData);
            params.put("DataSign", URLEncoder.encode(dataSign, "UTF-8"));
            params.put("DataType", "2");
            String reqUrl = ConfigContext.me().getConfigValueNullable("EXPRESS_BIRD_REQ_URL", String.class);
            String post = HttpUtil.post(reqUrl, params);
            return JSON.parseObject(post, JSONObject.class).getJSONArray("Traces");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("快递系统服务繁忙", e);
            throw new BusinessException(THE_EXPRESS_DELIVERY_SYSTEM_IS_BUSY);
        }
    }

    /**
     * MD5加密
     */
    private static String md5(String str) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes(StandardCharsets.UTF_8));
        byte[] result = md.digest();
        StringBuilder sb = new StringBuilder(32);
        for (byte b : result) {
            int val = b & 0xff;
            if (val <= 0xf) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(val));
        }
        return sb.toString().toLowerCase();
    }

    /**
     * Sign签名生成
     *
     * @param content 内容
     * @return DataSign签名
     */
    private static String encrypt(String content) throws Exception {
        String keyValue = ConfigContext.me().getConfigValueNullable("EXPRESS_BIRD_API_KEY", String.class);
        content = content + keyValue;
        byte[] src = md5(content).getBytes(StandardCharsets.UTF_8);
        return Base64Utils.encodeToString(src);
    }
}
